-- ======================================================================
-- Hell Lua Bus
-- 
-- Copyright 2012-2013Hell-Prototypes
--
-- http://www.hellprototypes.com/
--
-- This is free software, licensed under the terms of the GNU General
-- Public License as published by the Free Software Foundation.
-- ======================================================================
AVR_HVPP = require "mod_avr_hvpp_lite"

-- -----------------------------------------------------------------------------
-- WARNING:  ONLY TESTED WITH ATTINY2313
-- -----------------------------------------------------------------------------

-- -----------------------------------------------------------------------------
-- Errata ATtiny2313 Rev B : 
--   Parallel Programming does not work
--   Parallel Programming is not functioning correctly. Because of this, reprogramming of the
--   device is impossible if one of the following modes are selected: 
--     – In-System Programming disabled (SPIEN unprogrammed)
--     – Reset Disabled (RSTDISBL programmed)
-- -----------------------------------------------------------------------------

if not AVR_HVPP.device_open() then
	print("AVR_HVPP.device_open fail")
	return
end

if not AVR_HVPP.enter_HVPP_mode() then
	print("AVR_HVPP.enter_HVPP_mode fail")
end

print("Read device Signature Bytes:")
Target_Signature = {}

Target_Signature = AVR_HVPP.read_signature()
print("Target_Signature size = " .. #Target_Signature)
for i=1, #Target_Signature do
	print(string.format("    Target_Signature[%d] = 0x%x", i, Target_Signature[i]))
end

print("Ready to work:")
io.write("\r\n1: Release the pressed key to free XA0, Then Press Enter key to continue ...")
io.read()
print("")

print("1 Read device fuse Bytes:")
fuse = {}

fuse = AVR_HVPP.read_fuse()
print("fuse size = " .. #fuse)

for i=1, #fuse do
	print(string.format("    fuse[%d] = 0x%x", i, fuse[i]))
end

--[[
print("2 Write device fuse Bytes:")
wr_fuses = {0x64, 0xdf, 0xfe}--62 5d
for i=1, #wr_fuses do
	print(string.format("    wr_fuses[%d] = 0x%x", i, wr_fuses[i]))
end
ret = AVR_HVPP.write_fuses(wr_fuses)
print("write_fuses ret = " .. ret)
--]]

print("3 Read device fuse Bytes:")
fuse = {}

fuse = AVR_HVPP.read_fuse()
print("fuse size = " .. #fuse)

for i=1, #fuse do
	print(string.format("    fuse[%d] = 0x%x", i, fuse[i]))
end

print("Exit AVR_HVPP mode")
AVR_HVPP.exit_HVPP_mode()

if not AVR_HVPP.device_close() then
	print("AVR_HVPP.device_close fail")
end